package com.dmbjz.handler;

import com.dmbjz.entity.SecurityUser;
import com.dmbjz.serivice.inter.WeChatService;
import com.dmbjz.utils.TokenManager;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.Collection;


/*登录成功发送消息操作*/
public class LoginSuccessSendMessageHandler extends SavedRequestAwareAuthenticationSuccessHandler {


    private WeChatService weChatService;
    private TokenManager tokenManager;
    private RedisTemplate redisTemplate;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws ServletException, IOException {

        super.onAuthenticationSuccess(request, response, authentication);
        logger.info(String.format("IP %s，用户 %s， 于 %s 成功登录系统。", request.getRemoteHost(), authentication.getName(), LocalDateTime.now()));
        weChatService.send(authentication.getName());

        /*将权限保存到Redis中*/
        SecurityUser securityUser = (SecurityUser) authentication.getPrincipal();
        String token = tokenManager.createToken(authentication.getName());                                 //根据用户名生成token
        redisTemplate.opsForValue().set(authentication.getName(),securityUser.getPermissionValueList());  //权限信息保存到Redis中
        logger.info("认证成功,Token为:"+token);
        //setDefaultTargetUrl("/dmbjz/index?token="+token);           //跳转的页面,将token返回
        redisTemplate.opsForValue().set("login"+authentication.getName(),token);  //权限信息保存到Redis中


    }

    public WeChatService getWeChatService() {
        return weChatService;
    }

    public void setWeChatService(WeChatService weChatService) {
        this.weChatService = weChatService;
    }

    public TokenManager getTokenManager() {
        return tokenManager;
    }

    public void setTokenManager(TokenManager tokenManager) {
        this.tokenManager = tokenManager;
    }

    public RedisTemplate getRedisTemplate() {
        return redisTemplate;
    }

    public void setRedisTemplate(RedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }


}
